package cn.yuanqiao.archive.wenjianzhengli.service.impl;/**
 * @author 赵常飞
 * @date 2023/6/20 20:14
 */

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.impl.TenantMijiComparisonTableServiceImpl;
import cn.yuanqiao.archive.wenjianzhengli.domain.TenantTablehead;
import cn.yuanqiao.archive.wenjianzhengli.mapper.WenjianhuishouzhanMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.IWenjianhuishouzhanService;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @AUTHOR:赵常飞
 * @date 2023/6/20 20:14
 */
@Service
public class WenjianhuishouzhanServiceImpl implements IWenjianhuishouzhanService {

    @Autowired
    private WenjianhuishouzhanMapper wenjianhuishouzhanMapper;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Autowired
    private WenjianzhengliServiceImpl wenjianzhengliService;

    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private TenantMdataListMapper mdataListMapper;
    @Autowired
    TenantMijiComparisonTableServiceImpl mijiComparisonTableService;

    @Override
    public List<Map<String, Object>> getdatalist(JSONObject json) {
        JSONArray statearray = json.getJSONArray("state");
        int[] states = new int[statearray.size()];
        for (int i = 0; i < statearray.size(); i++) {
            states[i] = (int) statearray.get(i);
        }
        String fields = json.getString("fields");//BGQX,MJ,TITLE
        Long categoryId = json.getLong("categoryId");
        Integer type = json.getInteger("type"); //0:件 1:卷 3:项目
        Long parentId = json.getLong("parentId");
        String level = json.getString("level"); //jian juan efile xiangmu
        String orderstr = json.getString("order");//表头点击排序
        Long menuId = json.getLong("menuId");
        String qzh = json.getString("qzh");
        JSONArray jsonArray = json.getJSONArray("searchcolumn");
        if (null == jsonArray) {
            jsonArray = new JSONArray();
        }
        StringBuilder sb = new StringBuilder();
        if (jsonArray.size() > 0) {
            wenjianzhengliService.concatQueryCondition(jsonArray, sb);
        }
        String mjWhere = "";
        if (FBswitch) {
            //查看是否有MJ字段
            TenantMdataList select = new TenantMdataList();
            select.setFieldName("MJ");
            select.setType(type);
            int num = mdataListMapper.getNumByFieldName(select, new TenantMdataGroup().getTableName());
            if (num > 0) {
                List<TenantRyMjDzb> getdamjbyrymj = mijiComparisonTableService.getdamjbyrymj();
                mjWhere = (" and MJ in ('" + getdamjbyrymj.stream().map(m -> m.getDaMj()).collect(Collectors.joining("','")) + "') ");
            }
        }

        if (StringUtils.isNotBlank(qzh) && !"-1".equals(qzh)&&categoryId==null) {
            List<Map<String, Object>> categoryIds = wenjianhuishouzhanMapper.selectTableData(
                    SecurityUtils.getTenantCode() + "_CATEGORY", " ID,FOLDER_TABLE_NAME,ITEM_TABLE_NAME,FILE_TABLE_NAME ", " FONDS_CODE ='" + qzh + "'");
             if(sb.length()==0){
                 sb.append(" SUB_TABLE_NAME in ('" + categoryIds.stream().map(m -> String.valueOf("jian".equals(level) ? m.get("FILE_TABLE_NAME")
                         : "juan".equals(level) ? m.get("FOLDER_TABLE_NAME") : m.get("ITEM_TABLE_NAME"))).collect(Collectors.joining("','")) + "') and");
             }else{
                 sb.append(" and SUB_TABLE_NAME in ('" + categoryIds.stream().map(m -> String.valueOf("jian".equals(level) ? m.get("FILE_TABLE_NAME")
                         : "juan".equals(level) ? m.get("FOLDER_TABLE_NAME") : m.get("ITEM_TABLE_NAME"))).collect(Collectors.joining("','")) + "') and ");

             }
        }

        List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
        if (null != parentId) {
            String subtablename = json.getString("subtablename").toUpperCase();
            TenantCategory tenantCategory = new TenantCategory();
            String catetablename = tenantCategory.getTableName();
            Map<String, String> cateinfo = wenjianhuishouzhanMapper.getcateidbysub(catetablename, subtablename).get(0);

            String relatable = "";//关联表
            String searchtablename = "";//要查询的表
            String parentfield = "";//父字段
            String sonfield = "";//子字段
            int fieldneedtype = 0;//元数据明细  需要层级 避免出现父子层级一个为字典项,一个不为字典项的问题
            if ("juan".equals(level)) { //查 项目 和 卷 关联
                TenantItemFolder tenantItemFolder = new TenantItemFolder();
                relatable = tenantItemFolder.getTableName();
                searchtablename = cateinfo.get("FOLDER_TABLE_NAME");
                parentfield = "ITEM_ID";
                sonfield = "FOLDER_ID";
                fieldneedtype = 1;
            } else if ("jian".equals(level)) { //查 卷和件 关联
                TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
                relatable = tenantYqdaFolder.getTableName();
                searchtablename = cateinfo.get("FILE_TABLE_NAME");
                parentfield = "FOLDER_ID";
                sonfield = "YQDA_ID";
                fieldneedtype = 0;
            }
            //fields=formatfields(fields,categoryId,Long.parseLong(cateinfo.get("GROUP_ID")),fieldneedtype);//处理字典项等字段

            if (null != orderstr && !"".equals(orderstr)) {
                orderstr = " order by " + orderstr;
            } else {
                String applyorderstr = tenantMdataListService.getorder(Long.parseLong(String.valueOf(cateinfo.get("ID"))), menuId, fieldneedtype);
                if (null != applyorderstr && !"".equals(applyorderstr)) {
                    String[] split = applyorderstr.split(",");
                    List<String> order = new ArrayList<>();
                    for (String s : split) {
                        if (!s.contains(" NONE")) {
                            order.add(s);
                        }
                    }
                    if (order != null && order.size() > 0)
                        orderstr = " order by " + order.stream().collect(Collectors.joining(","));
                }
            }
            PageUtils.startPage();
            String[] split = fields.split(",");
            boolean flag = false;
            for (int i = 0; i < split.length; i++) {
                if ("STATE".equals(split[i])) {
                    flag = true;
                }
            }
            if (flag) {
                fields = fields + ",ID,SUB_TABLE_NAME";
            } else {
                fields = fields + ",ID,SUB_TABLE_NAME,STATE";
            }
            datalist = wenjianhuishouzhanMapper.getdatalistbyparentId(searchtablename, relatable, parentfield, sonfield, fields, parentId, orderstr, sb.toString(), mjWhere);
            return datalist;
        }
        if (null == categoryId) { //所有门类
            String allTableName = "";
            String idfield = "";
            if (0 == type) {//件
                TenantYqda tenantYqda = new TenantYqda();
                allTableName = tenantYqda.getTableName();
                idfield = "DA_ID as ID,";
            } else if (1 == type) {//卷
                TenantYqFolder tenantYqFolder = new TenantYqFolder();
                allTableName = tenantYqFolder.getTableName();
                idfield = "FOLDER_ID as ID,";
            }/*else if(2==type){//电子文件
                TenantYqdaDocument tenantYqdaDocument=new TenantYqdaDocument();
                allTableName=tenantYqdaDocument.getTableName();
            }*/ else if (3 == type) {//项目
                TenantYqItem tenantYqItem = new TenantYqItem();
                allTableName = tenantYqItem.getTableName();
                idfield = "ITEM_ID as ID,";
            }
            //fields=formatfields(fields,categoryId,null,type);//处理字典项等字段
            if (null != orderstr && !"".equals(orderstr)) {
                orderstr = " order by " + orderstr;
            } else {
                TenantTablehead tablehead = new TenantTablehead();
                tablehead.setZltype(type);
                tablehead.setTablemenuId(menuId);
                tablehead.setQzh(qzh);
                String gethead = gethead(tablehead);
                if (null != gethead && !"".equals(gethead)) {
                    String[] split = gethead.split(",");
                    List<String> order = new ArrayList<>();
                    for (String s : split) {
                        if (!s.contains(" NONE")) {
                            order.add(s);
                        }
                    }
                    if (order != null && order.size() > 0)
                        orderstr = " order by " + order.stream().collect(Collectors.joining(","));
                }

            }
            PageUtils.startPage();
            String[] split = fields.split(",");
            boolean flag = false;
            for (int i = 0; i < split.length; i++) {
                if ("STATE".equals(split[i])) {
                    flag = true;
                }
            }
            if (flag) {
                fields = idfield + fields + ",SUB_TABLE_NAME";
            } else {
                fields = idfield + fields + ",SUB_TABLE_NAME,STATE";
            }
            datalist = wenjianhuishouzhanMapper.getdatalistnocate(fields, allTableName, states, orderstr,sb.toString(), mjWhere);
        } else {
            String sub = "";
            if (0 == type) {//件层
                sub = "file_table_name";
            } else if (1 == type) {
                sub = "folder_table_name";
            } else if (3 == type) {
                sub = "item_table_name";
            }
            //fields=formatfields(fields,categoryId,null,type);//处理字典项等字段
            TenantCategory tenantCategory = new TenantCategory();
            String catetablename = tenantCategory.getTableName();
            String subtablename = wenjianhuishouzhanMapper.getSubTableName(categoryId, sub, catetablename);
            if (null != orderstr && !"".equals(orderstr)) {
                orderstr = " order by " + orderstr;
            } else {
                String applyorderstr = tenantMdataListService.getorder(categoryId, menuId, type);
                if (null != applyorderstr && !"".equals(applyorderstr)) {
                    String[] split = applyorderstr.split(",");
                    List<String> order = new ArrayList<>();
                    for (String s : split) {
                        if (!s.contains(" NONE")) {
                            order.add(s);
                        }
                    }
                    if (order != null && order.size() > 0)
                        orderstr = " order by " + order.stream().collect(Collectors.joining(","));
                }
            }
            PageUtils.startPage();
            String[] split = fields.split(",");
            boolean flag = false;
            for (int i = 0; i < split.length; i++) {
                if ("STATE".equals(split[i])) {
                    flag = true;
                }
            }
            if (flag) {
                fields = fields + ",ID,'" + subtablename + "' as SUB_TABLE_NAME";
            } else {
                fields = fields + ",ID,'" + subtablename + "' as SUB_TABLE_NAME,STATE";
            }
            datalist = wenjianhuishouzhanMapper.getdatalistbycateid(subtablename, fields, states, orderstr, sb.toString(), mjWhere);
        }
        return datalist;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String restore(JSONObject json) {
        JSONArray data = json.getJSONArray("data");
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();//获取租户门类表
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();//获取件总表
        TenantYqFolder tenantYqFolder = new TenantYqFolder();
        String allvtable = tenantYqFolder.getTableName();//获取案卷总表
        TenantYqItem tenantYqItem = new TenantYqItem();
        String allitemtable = tenantYqItem.getTableName();//获取项目总表
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        String fvtable = tenantYqdaFolder.getTableName();//获取卷件关联表
        TenantItemFolder tenantItemFolder = new TenantItemFolder();
        String itemvtable = tenantItemFolder.getTableName();//获取项目卷关联表
        StringBuffer returnsb = new StringBuffer();
        int success = 0;//判断是否有恢复数据 0 1
        //需要每个循环,可能是项目/卷/件,不根据层级和门类再去判断,多一次查询,减少逻辑
        for (int i = 0; i < data.size(); i++) {
            Map<String, String> jsoni = (Map) data.get(i);
            int state = Integer.parseInt(String.valueOf(jsoni.get("state")));
            String subtablename = jsoni.get("subTableName").toUpperCase();
            Map<String, String> cateinfo = wenjianhuishouzhanMapper.getcateidbysub(catetablename, subtablename).get(0);
            String datatype = subtablename.substring(subtablename.length() - 3, subtablename.length() - 2);//数据是哪个层级
            String catetype = String.valueOf(cateinfo.get("TYPE"));
            if ("0".equals(catetype)) {//门类为组件类型,直接恢复
                //总表 总表id 分表 分表 id
                wenjianhuishouzhanMapper.restore(allftable, "DA_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));
                success = 1;
            } else if ("1".equals(catetype)) {//门类为组卷类型,卷可以直接恢复并恢复件;件需要判断卷是否被删除或者已归档,卷被删除不能恢复,卷已归档等于件少走了审批,不允许归档
                if ("V".equals(datatype)) {//门类为组卷类型,并且当前数据层级为卷,卷可以直接恢复并恢复件
                    wenjianhuishouzhanMapper.restore(allvtable, "FOLDER_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//恢复卷
                    wenjianhuishouzhanMapper.restore(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//恢复件
                    success = 1;
                } else if ("F".equals(datatype)) {//门类为组卷类型,并且当前数据层级为件,判断卷是否删除状态或归档状态不一致
                    Map<String, String> foldermap = wenjianhuishouzhanMapper.getparentmapbyson(cateinfo.get("FOLDER_TABLE_NAME"), "ID", fvtable, "DA_ID", "FOLDER_ID", Long.parseLong(String.valueOf(jsoni.get("id"))));//获取卷层信息
                    if (foldermap != null && !String.valueOf(foldermap.get("STATE")).equals(String.valueOf(state))) {//状态不一致不允许恢复
                        returnsb.append("文件《" + jsoni.get("title") + "》与对应卷状态不一致不允许恢复!");
                    } else if (foldermap != null && "1".equals(String.valueOf(foldermap.get("IS_DEL")))) {//卷删除件不能恢复
                        returnsb.append("文件《" + jsoni.get("title") + "》的对应卷是已删除状态不允许恢复!");
                    } else {//可以恢复
                        wenjianhuishouzhanMapper.restore(allftable, "DA_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));
                        success = 1;
                    }
                }
            } else if ("3".equals(catetype)) {//门类为项目类型,项目直接恢复,并恢复卷件;卷层判断项目归档和删除状态;件层判断项目/卷归档不一致和删除状态
                if ("X".equals(datatype)) {//门类为项目类型,并且当前数据层级为项目,直接恢复
                    wenjianhuishouzhanMapper.restore(allitemtable, "ITEM_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//恢复项目
                    wenjianhuishouzhanMapper.restore(allvtable, "FOLDER_ID", cateinfo.get("FOLDER_TABLE_NAME"), "ID", "select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")));//恢复卷
                    wenjianhuishouzhanMapper.restore(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where folder_id in(select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")) + ")");//恢复件
                    //项目和卷可以单独关联
                    wenjianhuishouzhanMapper.restore(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where item_id=" + String.valueOf(jsoni.get("id")));
                    success = 1;
                } else if ("V".equals(datatype)) {//门类为项目,当前数据为卷,判断项目层状态不一致和删除状态
                    Map<String, String> itemmap = wenjianhuishouzhanMapper.getparentmapbyson(cateinfo.get("ITEM_TABLE_NAME"), "ID", itemvtable, "FOLDER_ID", "ITEM_ID", Long.parseLong(String.valueOf(jsoni.get("id"))));//获取项目层信息
                    if (itemmap != null && !String.valueOf(itemmap.get("STATE")).equals(String.valueOf(state))) {//状态不一致不允许恢复
                        returnsb.append("案卷《" + jsoni.get("title") + "》与对应项目状态不一致不允许恢复!");
                    } else if (itemmap != null && "1".equals(String.valueOf(itemmap.get("IS_DEL")))) {//项目删除卷不能恢复
                        returnsb.append("案卷《" + jsoni.get("title") + "》的对应项目是已删除状态不允许恢复!");
                    } else {
                        wenjianhuishouzhanMapper.restore(allvtable, "FOLDER_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//恢复卷
                        wenjianhuishouzhanMapper.restore(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//恢复件
                        success = 1;
                    }
                } else if ("F".equals(datatype)) {//门类为项目,当前数据层级为件,需判断项目和卷
                    Map<String, Object> foldermap = wenjianhuishouzhanMapper.getparentmapbyson(cateinfo.get("FOLDER_TABLE_NAME"), "ID", fvtable, "DA_ID", "FOLDER_ID", Long.parseLong(String.valueOf(jsoni.get("id"))));//获取项目层信息
                    //项目被删除,案卷未删除情况不会出现,不再判断件和项目的关联
                    Map<String, String> itemmap = wenjianhuishouzhanMapper.getparentmapbyson1(cateinfo.get("ITEM_TABLE_NAME"), "ID", fvtable, "DA_ID", "ITEM_ID", Long.parseLong(String.valueOf(jsoni.get("id"))));//获取项目层信息
                    if (foldermap != null && !(String.valueOf(foldermap.get("STATE"))).equals(String.valueOf(state))) {//件卷状态不一致
                        returnsb.append("文件《" + jsoni.get("title") + "》与对应案卷状态不一致不允许恢复!");
                    } else if (foldermap != null && "1".equals(String.valueOf(foldermap.get("IS_DEL")))) {//案卷删除状态
                        returnsb.append("文件《" + jsoni.get("title") + "》的对应案卷是已删除状态不允许恢复!");
                    } else if (itemmap != null && !(String.valueOf(itemmap.get("STATE"))).equals(String.valueOf(state))) {
                        returnsb.append("文件《" + jsoni.get("title") + "》与对应项目状态不一致不允许恢复!");
                    } else if (itemmap != null && "1".equals(String.valueOf(itemmap.get("IS_DEL")))) {
                        returnsb.append("文件《" + jsoni.get("title") + "》的对应项目是已删除状态不允许恢复!");
                    } else {
                        wenjianhuishouzhanMapper.restore(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", String.valueOf(jsoni.get("id")));//恢复件
                        success = 1;
                    }
                }
            }
        }
        if (success == 0) {//说明都是不符合条件
            return returnsb.toString();
        } else {
            return "恢复成功!" + returnsb.toString();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<List> delete(JSONObject json) {
        JSONArray data = json.getJSONArray("data");
        TenantCategory tenantCategory = new TenantCategory();
        String catetablename = tenantCategory.getTableName();//获取租户门类表
        TenantYqda tenantYqda = new TenantYqda();
        String allftable = tenantYqda.getTableName();//获取件总表
        TenantYqFolder tenantYqFolder = new TenantYqFolder();
        String allvtable = tenantYqFolder.getTableName();//获取案卷总表
        TenantYqItem tenantYqItem = new TenantYqItem();
        String allitemtable = tenantYqItem.getTableName();//获取项目总表
        TenantYqdaFolder tenantYqdaFolder = new TenantYqdaFolder();
        String fvtable = tenantYqdaFolder.getTableName();//获取卷件关联表
        TenantItemFolder tenantItemFolder = new TenantItemFolder();
        String itemvtable = tenantItemFolder.getTableName();//获取项目卷关联表
        List<List> doclist = new ArrayList<List>();
        for (int i = 0; i < data.size(); i++) {
            Map<String, String> jsoni = (Map) data.get(i);
            String subtablename = jsoni.get("subTableName").toUpperCase();
            Map<String, String> cateinfo = wenjianhuishouzhanMapper.getcateidbysub(catetablename, subtablename).get(0);
            String datatype = subtablename.substring(subtablename.length() - 3, subtablename.length() - 2);//数据是哪个层级
            String catetype = String.valueOf(cateinfo.get("TYPE"));
            if ("0".equals(catetype)) {//删除件主表分表
                wenjianhuishouzhanMapper.delete(allftable, "DA_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));
                List list = getdeleteFile("DA_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                doclist.add(list);
                wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), String.valueOf(jsoni.get("id")));//删除文件表

            } else if ("1".equals(catetype)) {//门类为组卷
                if ("V".equals(datatype)) {//当前数据为卷,需要删除卷&件
                    wenjianhuishouzhanMapper.delete(allvtable, "FOLDER_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//删除卷
                    wenjianhuishouzhanMapper.delete(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//删除件
                    List list = getdeleteFile("FOLDER_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                    doclist.add(list);
                    wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//删除文件表
                    wenjianhuishouzhanMapper.deleterela(fvtable, "FOLDER_ID", String.valueOf(jsoni.get("id")));//删除关联卷件表数据
                } else if ("F".equals(datatype)) {//当前数据为件,删除件
                    wenjianhuishouzhanMapper.delete(allftable, "DA_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//删除件
                    List list = getdeleteFile("DA_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                    doclist.add(list);
                    wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), String.valueOf(jsoni.get("id")));//删除文件表
                    wenjianhuishouzhanMapper.deleterela(fvtable, "DA_ID", String.valueOf(jsoni.get("id")));//删除关联卷件表数据
                }
            } else if ("3".equals(catetype)) {//项目类型
                if ("X".equals(datatype)) {//当前数据为项目,需要删除项目&卷&件
                    wenjianhuishouzhanMapper.delete(allitemtable, "ITEM_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//删除项目
                    wenjianhuishouzhanMapper.delete(allvtable, "FOLDER_ID", cateinfo.get("FOLDER_TABLE_NAME"), "ID", "select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")));//删除卷
                    wenjianhuishouzhanMapper.delete(allftable, "DA_ID", cateinfo.get("FILE_TABLE_NAME"), "ID", "select da_id from " + fvtable + " where folder_id in(select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")) + ")");//删除件
                    List list = getdeleteFile("ITEM_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                    doclist.add(list);
                    wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), "select da_id from " + fvtable + " where folder_id in(select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")) + ")");//删除文件表
                    wenjianhuishouzhanMapper.deleterela(fvtable, "FOLDER_ID", "select folder_id from " + itemvtable + " where item_id=" + String.valueOf(jsoni.get("id")));//删除关联卷件表数据
                    wenjianhuishouzhanMapper.deleterela(itemvtable, "ITEM_ID", String.valueOf(jsoni.get("id")));//删除项目卷关联
                } else if ("V".equals(datatype)) {//当前数据为卷,需要删除卷&件
                    wenjianhuishouzhanMapper.delete(allvtable, "FOLDER_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//删除卷
                    wenjianhuishouzhanMapper.delete(allftable, "DA_ID", subtablename, "ID", "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//删除件
                    List list = getdeleteFile("FOLDER_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                    doclist.add(list);
                    wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), "select da_id from " + fvtable + " where folder_id=" + String.valueOf(jsoni.get("id")));//删除文件表
                    wenjianhuishouzhanMapper.deleterela(itemvtable, "FOLDER_ID", String.valueOf(jsoni.get("id")));//删除项目卷关联
                    wenjianhuishouzhanMapper.deleterela(fvtable, "FOLDER_ID", String.valueOf(jsoni.get("id")));//删除件卷关联
                } else if ("F".equals(datatype)) {//当前数据为件,需要删除件
                    wenjianhuishouzhanMapper.delete(allftable, "DA_ID", subtablename, "ID", String.valueOf(jsoni.get("id")));//删除件
                    List list = getdeleteFile("DA_ID", String.valueOf(jsoni.get("id")), fvtable, itemvtable, cateinfo.get("EFILE_TABLE_NAME"));
                    doclist.add(list);
                    wenjianhuishouzhanMapper.deleteefile(cateinfo.get("EFILE_TABLE_NAME"), String.valueOf(jsoni.get("id")));//删除文件表
                    wenjianhuishouzhanMapper.deleterela(fvtable, "DA_ID", String.valueOf(jsoni.get("id")));//删除件卷关联
                }
            }
        }
        return doclist;
    }

    /**
     * 删除文件
     *
     * @param list
     */
    @Override
    public void deleteefile(List<List> list) {
        try {
            for (int i = 0; i < list.size(); i++) {
                List<Map<String, String>> sonlist = list.get(i);
                for (int j = 0; j < sonlist.size(); j++) {
                    String efilepath = sonlist.get(j).get("DOC_MNT") + sonlist.get(j).get("PATH");
                    if (!"".equals(efilepath) && null != efilepath) {
                        File file = new File(efilepath);
                        file.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //出错时不处理
        }

    }

    @Override
    public Long getcateidbyid(JSONObject json) {
        Long id = json.getLong("id");
        String type = json.getString("type");
        String alltablename = "";
        String tablefield = "";
        String idfield = "";
        if ("x".equals(type)) {
            alltablename = new TenantYqItem().getTableName();
            tablefield = "ITEM_TABLE_NAME";
            idfield = "ITEM_ID";
        } else if ("v".equals(type)) {
            alltablename = new TenantYqFolder().getTableName();
            tablefield = "FOLDER_TABLE_NAME";
            idfield = "FOLDER_ID";
        } else if ("f".equals(type)) {
            alltablename = new TenantYqda().getTableName();
            tablefield = "FILE_TABLE_NAME";
            idfield = "DA_ID";
        }
        return wenjianhuishouzhanMapper.getcateidbydaid(new TenantCategory().getTableName(), alltablename, tablefield, idfield, id);
    }

    @Override
    public int addhead(TenantTablehead tablehead) {
        if (null == tablehead.getContent() || "".equals(tablehead.getContent())) {
            wenjianhuishouzhanMapper.deletehead(tablehead);
        } else {
            String gethead = gethead(tablehead);
            if (null == gethead || "".equals(gethead)) {
                String content = tablehead.getContent();
                content = content.replace("$", " ").toUpperCase();
                tablehead.setContent(content);
                wenjianhuishouzhanMapper.addhead(tablehead);
            } else {
                String content = tablehead.getContent();
                content = content.replace("$", " ").toUpperCase();
                tablehead.setContent(content);
                wenjianhuishouzhanMapper.updatehead(tablehead);
            }
        }
        return 1;
    }

    @Override
    public String gethead(TenantTablehead tablehead) {
        String headString = wenjianhuishouzhanMapper.gethead(tablehead);
        return headString;
    }

    /**
     * 删除文件
     *
     * @param type       id类型
     * @param id         id
     * @param fvtable    fv关联表
     * @param itemvtable itemv关联表
     */
    private List getdeleteFile(String type, String id, String fvtable, String itemvtable, String doctable) {
        String idsql = "";
        if ("DA_ID".equals(type)) {//传的是档案id
            idsql = id;
        } else if ("FOLDER_ID".equals(type)) {//传的是案卷id
            idsql = "select da_id from " + fvtable + " where folder_id=" + id;
        } else if ("ITEM_ID".equals(type)) {//传的是项目id
            idsql = "select da_id from " + fvtable + " where folder_id in(select folder_id from " + itemvtable + " where item_id=" + id + ")";
        }
        return wenjianhuishouzhanMapper.getdeleteFile(doctable, idsql);
    }

    /**
     * 将字典项处理成sql,目前由前端处理,此方法废弃
     *
     * @param fields
     * @param categoryId
     * @param groupId
     * @param needtype
     * @return
     */
    private String formatfields(String fields, Long categoryId, Long groupId, Integer needtype) {
        fields = "'" + fields.replace(",", "','") + "'";
        String newfields = "";
        TenantMdataList tenantMdataList = new TenantMdataList();
        String mdatalisttable = tenantMdataList.getTableName();
        String appendsql = "";
        if (null == categoryId) {//未指定门类
            if (null == groupId) {//全部
                appendsql = " and type=" + needtype;
            } else {//拿到了groupId
                appendsql = " and group_id=" + groupId + " and type=" + needtype;
            }
        } else {//有具体门类
            TenantCategory tenantCategory = new TenantCategory();
            appendsql = " and group_id=(select group_id from " + tenantCategory.getTableName() + " where id=" + categoryId + ") and type=" + needtype;
        }
        List<Map> fieldlist = wenjianhuishouzhanMapper.getfieldlist(mdatalisttable, fields, appendsql);
        TenantSysDictData tenantSysDictData = new TenantSysDictData();
        for (int i = 0; i < fieldlist.size(); i++) {
            if ("5".equals(fieldlist.get(i).get("SHOWTYPE"))) {
                newfields += "(select dict_label from " + tenantSysDictData.getTableName() + " where dict_type='" + fieldlist.get(i).get("FIELD_NAME") + "' and status=0 and dict_value=" + fieldlist.get(i).get("FIELD_NAME") + ") as " + fieldlist.get(i).get("FIELD_NAME") + ",";
            } else {
                newfields += fieldlist.get(i).get("FIELD_NAME") + ",";
            }
        }
        newfields = newfields.substring(0, newfields.length() - 1);
        return newfields;
    }
}
